<template>
  <div class="c-mixcheck">
    <slot></slot>
  </div>
</template>

<script type="text/ecmascript-6">
import { isArray, findComponentsDownward } from '../utils'

export default {
  name: 'Mixcheck',
  props: {
    value: {
      type: [Array, String, Number],
      default: '',
      required: true
    }
  },
  methods: {
    updateModel () {
      const { value, $children: childrens } = this
      for (const child of childrens) {
        child.model = value
        child.currentValue = false
      }
      const radioChildrens = findComponentsDownward(this, 'RadioItem')
      const checkChildrens = findComponentsDownward(this, 'CheckItem')
      if (isArray(value)) {
        for (const ret of checkChildrens) {
          ret.currentValue = value.indexOf(ret.label) > -1
        }
      } else {
        const index = radioChildrens.findIndex(ret => ret.label === value)
        if (index > -1) radioChildrens[index].currentValue = true
      }
    },
    change (data) {
      this.$emit('input', data)
      this.$emit('on-change', data)
    }
  },
  watch: {
    value: {
      handler (nVal, oVal) {
        this.updateModel()
      },
      deep: true
    }
  }
}
</script>
